<?php

/**
 * 取硬盘设备信息
 * @param string 设备路径
 */
function getDiskInfo($device_path){
    $awk = 'awk \'{ printf("{\"partition\":\"%s\",\"total\":%s,\"used\":%s,\"free\":%s,\"mount\":\"%s\"},\n",$1,$2,$3,$4,$6) }\'';
    $cmd = "df --block-size=1 | grep -E \"$device_path\" | sort | $awk";
    exec($cmd,$output);
    $output = implode('',$output);
    $res = "[$output";
    $res[strlen($res) - 1] = ']';
    return json_decode($res,true);
}

/**
 * 构造标准响应数组结构
 * @param int $status 状态
 * @param mixed $data 有效数据
 * @param string $msg 服务器消息
 * @return array
 *
 */
function makeRes($status = 1, $data = null, $msg = "OK"){
    return [
        'status'=>$status,
        'data'=>$data,
        'msg'=>$msg
    ];
}

class SysInfo {
    static function getNetworkInterfaces() {
        exec('cat /proc/net/dev | sed \'1,2d\' | awk \'{print $1}\' | awk -F: \'{print $1}\'', $res);
        return $res;
    }

    static function getNetworkInterfaceInfo($interface_name) {
        $cmd = 'cat /proc/net/dev | sed \'1,2d\' | grep -E \'^\\s+?'. $interface_name .':\' | awk \'{printf("{\"recv\":%s, \"send\":%s}",$2,$10)}\'';
        exec($cmd, $res);
        return json_decode($res[0], true);
    }

    static function getNetworkInterfacesInfo($interface_names = '') {
        $data = [];
        if ($interface_names == '') {
            $interface_names = self::getNetworkInterfaces();
        }
        if (gettype($interface_names) == 'string') {
            $interface_names = [$interface_names];
        }
        foreach ($interface_names as $itf) {
            $data[$itf][0] = self::getNetworkInterfaceInfo($itf);
        }
        usleep(200000);
        foreach ($interface_names as $itf) {
            $data[$itf][1] = self::getNetworkInterfaceInfo($itf);
        }
        $res = [];
        foreach ($data as $itf => &$value) {
            $res[$itf]['recv_total'] = $value[0]['recv'];
            $res[$itf]['send_total'] = $value[0]['send'];
            $res[$itf]['recv_speed'] = ($value[1]['recv'] - $value[0]['recv'])*5;
            $res[$itf]['send_speed'] = ($value[1]['send'] - $value[0]['send'])*5;
            unset($value);
        }
        return $res;
    }
}